package org.example.intern.config;

import lombok.extern.slf4j.Slf4j;
import org.example.intern.config.exception.ServiceException;
import org.example.intern.utils.Rest;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常捕获
 */
//@ControllerAdvice 返回视图、页面
@Slf4j
@RestControllerAdvice // 返回的字符串
public class GlobalHandleController {
    @ExceptionHandler(ConstraintViolationException.class)
    public Rest validationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        List<String> collect = violations.stream().map(o -> o.getMessage()).collect(Collectors.toList());
        System.out.println(collect);
        return Rest.faild("校验出现异常" + collect.toString());
    }

    /**
     * 请求参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Rest bindException(BindException e){
        FieldError error = e.getFieldError();
        return Rest.faild(error.getDefaultMessage());
    }

    /**
     * 请求方法异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Rest methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error(e.getMessage());
        return Rest.faild("验证失败:" + e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public Rest nullPointerException(NullPointerException e){
        log.error("空值异常",e.getMessage());
        return Rest.faild(e.getMessage());
    }

    /**
     * 自定义服务层异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public Rest httpExceptionHandle(ServiceException e){
        if (e.getDetailMessage() != null){
            log.error(e.getDetailMessage());
        }
        return Rest.faild(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Rest missingServletRequestParameterException(MissingServletRequestParameterException e){
        return Rest.faild(e.getParameterName() + "参数错误");
    }
}
